package com.qiyu.tech.gateway.event.task;

import com.qiyu.tech.gateway.event.InsertNodeEvent;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.TreeCache;
import org.apache.curator.framework.recipes.cache.TreeCacheListener;
import org.springframework.context.ApplicationEventPublisher;

@Slf4j
public class InsertNodeTask implements  Runnable{

    private ApplicationEventPublisher applicationEventPublisher;

    private CuratorFramework curatorFramework;

    private String insertRoot;

    public InsertNodeTask(CuratorFramework curatorFramework,ApplicationEventPublisher applicationEventPublisher,String insertRoot){
        this.curatorFramework = curatorFramework;
        this.applicationEventPublisher = applicationEventPublisher;
        this.insertRoot = insertRoot;
    }

    @Override
    public void run() {
        try {
            TreeCache treeCache = new TreeCache(curatorFramework, insertRoot);
            TreeCacheListener listener = (client1, event) -> {
                ChildData childData = event.getData();
                if(childData!=null){
                    byte[] data = childData.getData();
                    String insertId = new String(data);
                    applicationEventPublisher.publishEvent(new InsertNodeEvent(Long.valueOf(insertId)));
                }
            };
            treeCache.getListenable().addListener(listener);
            treeCache.start();
            log.info("=========== InsertNodeTask is started! ===========");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}